package com.bignerdranch.android.criminalintent;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.content.Context;

public class CriminalIntentJsonSerializer {
	private Context mContext;
	private String mFileName;
	
	public CriminalIntentJsonSerializer(Context c, String f){
		mContext = c;
		mFileName = f;
	}
	
	public void saveCrimes(ArrayList<Crime> crimes) throws JSONException, IOException{
		// Build Json array
		JSONArray jArray = new JSONArray();
		
		for (Crime c : crimes) {
			jArray.put(c.toJSON());
		}
		
		// Write file to disk
		Writer writer = null;
		try{
			OutputStream out = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
			writer = new OutputStreamWriter(out);
			writer.write(jArray.toString());
		}finally{
			if(writer != null){
				writer.close();
			}
		}		
	}
	
	public ArrayList<Crime> loadCrimes() throws JSONException, IOException{
		ArrayList<Crime> crimes = new ArrayList<Crime>();
		BufferedReader reader = null;
		try{
			// Open and read file
			InputStream is = mContext.openFileInput(mFileName);
			reader = new BufferedReader(new InputStreamReader(is));
			
			StringBuilder jsonString = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				jsonString.append(line);	
			}
			
			JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
			// Build json array
			for (int i = 0; i < array.length(); i++) {
				crimes.add(new Crime(array.getJSONObject(i)));
			}			
		}catch(FileNotFoundException fnfe){
			// Ignore
		}finally{
			if(reader != null){
				reader.close();
			}
		}
		return crimes;
	}
}
